package com.sysu.simulation.helper;

import android.app.Application;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;

import com.sysu.simulation.bean.User;

import cz.msebera.android.httpclient.Header;

public class AccountHelper {
    private User user;
    private Application application;
    private static final String USER_KEY_NAME = "info";

    private static AccountHelper instances;

    private AccountHelper(Application application) {
        this.application = application;
    }

    public static void init(Application application) {
        if (instances == null)
            instances = new AccountHelper(application);
        else {
            // reload from source
            instances.user = (User)CacheHelper.load(instances.application, User.class, USER_KEY_NAME);
        }
    }

    public static boolean isLogin() {
        return getUser().getId() != null;
    }

    public static String getUserId() {
        return getUser().getId();
    }

    public synchronized static User getUser() {
        if (instances == null) {
            return new User();
        }
        if (instances.user == null)
            instances.user = (User)CacheHelper.load(instances.application, User.class, USER_KEY_NAME);
        if (instances.user == null)
            instances.user = new User();
        return instances.user;
    }

    public static boolean updateUserCache(User user) {
        if(user==null) return false;
        instances.user = user;
        boolean succeed = false;
        succeed = CacheHelper.save(instances.application, user, USER_KEY_NAME);
        return succeed;
    }

    private static void clearUserCache() {
        CacheHelper.clearAll(instances.application);
    }

    public static boolean login(final User user, Header[] headers) {
        int count = 10;
        boolean succeed = false;
        // try to save to local
        while (!(succeed = updateUserCache(user)) && count-- > 0) {
            SystemClock.sleep(100);
        }

        return succeed;
    }

    public static void logout(final View mlogoutButton) {
        instances.user = null;
        clearUserCache();
        // make sure that the user cache is clear
        mlogoutButton.postDelayed(new Runnable() {
            @Override
            public void run() {
                User user = (User) CacheHelper.load(instances.application, User.class, USER_KEY_NAME);
                if (user != null && user.getId() != null) mlogoutButton.postDelayed(this, 200);
            }
        }, 200);
    }
}
